package core.cwm;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import security.acl.AccessController;

import core.obj.Object;
import core.sub.Company;
import core.sub.Subject;

public class COISet {
	private List<COI> COIdata;
	static private COISet COIRecords = null;
	
	private COISet() {
		COIdata = new ArrayList<COI>();
	}
	
	public static COISet getInstance() {
		if(COIRecords == null)
			COIRecords = new COISet();
		return COIRecords;
	}
	
	public List<COI> getCOIs(Company C) {
		List<COI> companyCOIs = new ArrayList<COI>();
		COI coi;
		for(Iterator<COI> iter = COIdata.iterator();iter.hasNext();) {
			coi = iter.next();
			if(coi.contains(C))
				companyCOIs.add(coi);
			
		}
		return companyCOIs;
	}
	
	public COI getCOI(String coiID) {
		for(COI coi:COIdata) {
			if(coi.getName().equals(coiID)) {
				return coi;
			}
		}
		
		return null;
	}
	
	public void addCOI(COI coi) {
		if(coi != null) {
			List<Company> L1 = coi.getCompanies();
			List<Company> L2 = coi.getCompanies();
			
			for(int i=0;i<L1.size()-1;i++) {
				for(int j=0;j<L2.size();j++) {
					if(!isSameCOI(L1.get(i), L2.get(j))) {
						// Two companies become competitors
						Set<Subject> subjects = PRRecord.getInstance().getAllSubjects();
						Set<Object> objects = new HashSet<Object>();
						for(Subject sub:subjects) {
							PRObject prObjs = PRRecord.getInstance().getPRObjects(sub);
							if(prObjs.getObjects() != null) {
								for(Object obj: prObjs.getObjects()) {
									if(CompanyRecord.getInstance().getCompanyDataSet(L1.get(i)).contains(obj)) {
										AccessController.getInstance().removeSubAccessObjFromDb(sub, obj);
										objects.add(obj);
										
									}
									if(CompanyRecord.getInstance().getCompanyDataSet(L2.get(j)).contains(obj)) {
										AccessController.getInstance().removeSubAccessObjFromDb(sub, obj);
										objects.add(obj);
									}
								}
								prObjs.removeAll(objects);
							}
						}
					}
				}
			}
			
			COIdata.add(coi);
		}
	}
	
	public COI addCOI(String coiID) {
		for(COI coi: COIdata) {
			if(coi.getName().equals(coiID)) {
				return coi;
			}
		}
		COI coi = new COI(coiID);
		COIdata.add(coi);
		return coi;
	}
	
	public boolean isSameCOI(Company C1, Company C2) {
		for(COI coi:COIdata) {
			if(coi.contains(C1) && coi.contains(C2))
				return true;
		}
		return false;
	}
	
	public void addCompanytoCOI(Company C, COI coi) {
		for(COI COI1: COIdata) {
			if(coi.getName().equals(COI1.getName())) {
				COI1.add(C);
				return;
			}
		}
	}
	
	public void removeCompanyFromCOI(Company C, COI coi) {
		for(COI COI1: COIdata) {
			if(coi.getName().equals(COI1.getName())) {
				COI1.remove(C);
				return;
			}
		}
	}	
}
